﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;

namespace BHair.kucunpandian
{
    public partial class frmqtck : Form
    {
        public frmqtck()
        {
            InitializeComponent();
        }
        string constr = ConfigurationManager.ConnectionStrings["BHair.Properties.Settings.BHairDBConnectionString"].ConnectionString;
        DataTable dt = new DataTable();
        string siweils = "";//四位流水号
        private void frmqtck_Load(object sender, EventArgs e)
        {
            djh();
            dt.Columns.Add("id", typeof(object));
            dt.Columns.Add("iid", typeof(string));
            dt.Columns.Add("iname", typeof(string));
            dt.Columns.Add("cksl", typeof(object));
            dt.Columns.Add("idj", typeof(decimal));
            dt.Columns.Add("ckje", typeof(decimal));
            dt.Columns.Add("iamount", typeof(decimal));
            for (int i = 0; i < 20; i++)
            {
                DataRow dr = dt.NewRow();
                dr["id"] = i + 1;
                dr["iid"] = "";
                dr["iname"] = "";
                dr["cksl"] = "";
                dr["idj"] = "0.00";
                dr["ckje"] = "0.00";
                dr["iamount"] = "0.00";
                dt.Rows.Add(dr);
            }
            gridControl1.DataSource = dt;
        }

        private void buttonEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            //选择往来单位
            frmwldw wl = new frmwldw();
            wl.ShowDialog();
            buttonEdit1.Text = pandian.khname;
        }

        private void buttonEdit2_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            //选择经手人
            frmjsr js = new frmjsr();
            js.ShowDialog();
            buttonEdit2.Text = pandian.jsr;
        }

        private void repositoryItemButtonEdit1_Click(object sender, EventArgs e)
        {
            /*
            //选择商品
            frmxzsp xz = new frmxzsp();
            xz.ShowDialog();
            dt.Rows[this.gridView1.FocusedRowHandle]["iid"] = pandian.iid;
            dt.Rows[this.gridView1.FocusedRowHandle]["iname"] = pandian.iname;
            dt.Rows[this.gridView1.FocusedRowHandle]["idj"] = pandian.idj;
            this.gridControl1.DataSource = dt;
            */
        }

        private void repositoryItemButtonEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {

            //选择商品
            frmxzsp xz = new frmxzsp();
            xz.ShowDialog();
            dt.Rows[this.gridView1.FocusedRowHandle]["iid"] = pandian.iid;
            dt.Rows[this.gridView1.FocusedRowHandle]["iname"] = pandian.iname;
            dt.Rows[this.gridView1.FocusedRowHandle]["idj"] = pandian.idj;
            dt.Rows[this.gridView1.FocusedRowHandle]["iamount"] = pandian.dqkc;
            this.gridControl1.DataSource = dt;
        }

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            int i = e.RowHandle; //行数，千万别用for循环来遍历gridview的行数
            object sl = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "idj"); //获取指定列SL数据
            object dj = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "cksl"); //获取指定列DJ数据
            if (sl != System.DBNull.Value && dj != System.DBNull.Value)    //判读object类型是否为空
            {
                decimal a = Convert.ToDecimal(sl);
                Decimal b = Convert.ToDecimal(dj);
                this.gridView1.GetDataRow(i)["ckje"] = (a * b).ToString();
            }
            // label6.Text= this.gridView1.Columns["ckje"].SummaryText;
            decimal sum = 0;
            for (int j = 0; j < dt.Rows.Count; j++)
            {
                sum += Convert.ToDecimal(Convert.ToSingle(dt.Rows[j][5].ToString()));
            }
            this.label6.Text = sum.ToString();
        }
        public void innertckd()
        {
            string sql = string.Format("INSERT INTO [出库单] ([单据号] ,[日期] ,[往来单位] ,[经手人] ,[单据金额] ,[收款金额] ,[优惠金额] ,[单据备注],hc) VALUES ('{0}'  ,'{1}' ,'{2}' ,'{3}' ,'{4}' ,'{5}'  ,'{6}'  ,'{7}',0)", txtdjh.Text, DateTime.Now.ToString("yyyy-MM-dd"), buttonEdit1.Text, buttonEdit2.Text, label6.Text, txtsk.Text, txtyh.Text, textBox1.Text);
            SqlConnection conn = new SqlConnection(constr);
            conn.Open();
            SqlCommand comm = new SqlCommand(sql, conn);
            comm.ExecuteNonQuery();
            conn.Close();
        }
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            //检查收款账户
            if (buttonEdit3.Text != string.Empty)
            {
                //检查收款金额
                decimal sk = (decimal.Parse(txtsk.Text) + decimal.Parse(txtyh.Text));
                if (sk >= decimal.Parse(label6.Text))
                {
                    //如果明细不合法则删除
                    // DataTable dts；
                    DataRow[] foundRow;
                    foundRow = dt.Select("iname=''", "");
                    foreach (DataRow row in foundRow)
                    {
                        dt.Rows.Remove(row);
                    }
                    gridControl1.DataSource = dt;
                    // MessageBox.Show(dt.Rows.Count.ToString());
                    pdkc();
                    
                    
                   // upkucun();
                  
                }
                else
                {
                    MessageBox.Show("收款金额小于单据金额，请正确填写");
                }
            }
            else
            {
                MessageBox.Show("请选择收款账户");
            }
        }
        public void innertsr()
        {
            SqlConnection conn = new SqlConnection(constr);
            conn.Open();
            string sql = string.Format("INSERT INTO [收入明细] ([djh] ,[skje] ,[zsje]  ,[djje],[yhje],[skfs] ,[djbz] ,[jsr]  ,[djrq] ,[班组])  VALUES  ('{0}'  ,'{1}' ,0.00 ,'{2}' ,'{3}' ,'{4}','{5}' ,'{6}'  ,'{7}' ,'{8}')", txtdjh.Text, txtsk.Text, label6.Text, txtyh.Text, buttonEdit3.Text, textBox1.Text, buttonEdit2.Text, DateTime.Now.ToString("yyyy-MM-dd"), chuanzhi.banzu);
            SqlCommand comm = new SqlCommand(sql, conn);
            comm.ExecuteNonQuery();
            conn.Close();
        }
        public void pdkc()
        {
            decimal upkc;
            bool fukucun=false;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                upkc = decimal.Parse(dt.Rows[i][6].ToString()) - decimal.Parse(dt.Rows[i][3].ToString());
                if (upkc < 0)
                {
                    fukucun = true;
                }
            }
            if (fukucun)
            {
                MessageBox.Show("有商品库存不足请检查后重新过账");
            }
            else
            {
                upkucun();
                innertckmx();
                innertsr();
                innertckd();
                djhshuaxin();
                MessageBox.Show("单据过账成功");
                this.Close();
            }
        }
        public void upkucun()
            {
            //修改库存
            SqlConnection conn = new SqlConnection(constr);
            conn.Open();
            decimal upkc;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                upkc = decimal.Parse(dt.Rows[i][6].ToString()) - decimal.Parse(dt.Rows[i][3].ToString());
                string sql = string.Format("UPDATE [items] SET [iamount] = '{0}'WHERE iid='{1}'",upkc, dt.Rows[i][1].ToString());
                SqlCommand comm = new SqlCommand(sql,conn);
                comm.ExecuteNonQuery();
            }
            conn.Close();
            }
        public void innertckmx()
        {
            SqlConnection conn = new SqlConnection(constr);
            conn.Open();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string sql = string.Format("INSERT INTO [其它出库明细]([单据号] ,[往来单位] ,[经手人] ,[商品编号]  ,[商品名称] ,[出库数量]  ,[出库单价]  ,[出库金额],日期) VALUES ('{0}' ,'{1}'   ,'{2}'  ,'{3}'  ,'{4}'  ,'{5}'  ,'{6}' ,'{7}','{8}')",txtdjh.Text,buttonEdit1.Text,buttonEdit2.Text, dt.Rows[i][1].ToString(), dt.Rows[i][2].ToString(), dt.Rows[i][3].ToString(), dt.Rows[i][4].ToString(), dt.Rows[i][5].ToString(),DateTime.Now.ToString("yyyy-MM-dd"));
                SqlCommand comm = new SqlCommand(sql,conn);
                comm.ExecuteNonQuery();
            }
            conn.Close();
        }
        private void simpleButton2_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        public void djh()
        {
            string lsh = "";
            try
            {
                SqlConnection conn = new SqlConnection(constr);
                conn.Open();
                string sql = "SELECT [qtck] FROM [djh]";
                SqlCommand comm = new SqlCommand(sql, conn);
                SqlDataReader sdr = comm.ExecuteReader();
                while (sdr.Read())
                {
                    lsh = sdr["qtck"].ToString();
                }
                string bs = "QT-";
                string time = DateTime.Now.ToString("yyyy-MM-dd");
                /*
                Random ran = new Random();
                int RandKey = ran.Next(10, 999);
                */
                int djlsh = Int32.Parse(lsh) + 1;
                siweils = string.Format("{0:00000}", djlsh);
                string djh = bs + time + "-" + chuanzhi.banzu + siweils;
                this.txtdjh.Text = djh;
                conn.Close();
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message);
            }

        }
        public void djhshuaxin()
        {
            try
            {
                SqlConnection conn = new SqlConnection(constr);
                conn.Open();

                string sql = string.Format("UPDATE [djh] SET [qtck] = '{0}'", siweils);
                SqlCommand comm = new SqlCommand(sql, conn);
                comm.ExecuteNonQuery();
            }
            catch { }
        }

        private void gridView1_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            //label6.Text = this.gridView1.Columns["ckje"].SummaryText;
        }

        private void buttonEdit3_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmxzzh ZH = new frmxzzh();
            ZH.ShowDialog();
            buttonEdit3.Text = pandian.skzh;
        }

        private void txtyh_TextChanged(object sender, EventArgs e)
        {
            try
            {
                txtsk.Text = (decimal.Parse(label6.Text) - decimal.Parse(txtyh.Text)).ToString();
            }
            catch { }
        }

        private void txtsk_TextChanged(object sender, EventArgs e)
        {
            try
            {
                txtyh.Text = (decimal.Parse(label6.Text) - decimal.Parse(txtsk.Text)).ToString();
            }
            catch { }
        }

        private void txtdjh_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                //根据单据号查并显示单据
                SqlConnection conn = new SqlConnection(constr);
                conn.Open();
                string sql =string.Format( "SELECT * FROM [其它出库明细] where 单据号='{0}'",txtdjh.Text);
                DataTable dt1 = new DataTable();
                SqlDataAdapter sda = new SqlDataAdapter(sql,conn);
                sda.Fill(dt1);
                gridControl1.DataSource = dt1;
                conn.Close();

            }
        }
    }
}
